﻿using JsonSerializationWithNewTonSoft.Entity.RubbishCategoryEntity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JsonSerializationWithNewTonSoft.Tools
{
    /// api文档https://www.juhe.cn/docs/api/id/375
    static public class RubbishCategoryHelper
    {
        //这里填写你自己的APPKey
        static private readonly string _appKey = "9f95c082170c008a9cf61a3317a284b";
        static private string _url= "";
        static private IDictionary<string, string> _parameters = null;
       static RubbishCategoryHelper()
        {
            _parameters = new Dictionary<string, string>();
            _parameters.Add("key", _appKey);
        }

        //垃圾分类基本信息
        //参数只有key
        static public async Task<string> GetAllAsync()
        {
            string result = "";
            //目标地址
            _url = "http://apis.juhe.cn/rubbish/category";         
            try
            {
                //创建HTTP请求辅助工具类，初始化当前目标地址，以及参数字典
                HttpHelper httpclient = new HttpHelper(_url, _parameters);
                //异步调用HTTP请求辅助工具类，异步Get请求方法
                result = await httpclient.GetDataAsync();

            }
            catch (Exception ex)
            {

                result = ex.Message;
            }
            return result;
        }

        static public async Task<List<Rubbish>> SearchByNameAsync(string rubbishName)
        {
            
            string resultJson = "";
            _url = "http://apis.juhe.cn/rubbish/search";
            _parameters.Add("q", rubbishName);
            try
            {
                HttpHelper httpclient = new HttpHelper(_url, _parameters);
                resultJson = await httpclient.PostDataAsync();

                if (resultJson.Contains("\"reason\":\"success\""))
                {
                    SearchResult resultObj = JsonConvert.DeserializeObject<SearchResult>(resultJson);
                    return resultObj.result.ToList();
                }
                else
                    return null;
            }
            catch (Exception ex)
            {

                Console.WriteLine(  ex.Message);
                return null;
            }
        }
    }
}
